<?php

use Upfor\UpforPHP\Model;
use SinoPHP\BbdBoss\Library\IpMonitor;

require_once __DIR__ . '/../UpforPHP/bootstrap.php';
require_once __DIR__ . '/../vendor/autoload.php';

$params = $argv;


// 获取所有绑定服务器组的IP
$ipIdList = model("ServerGroupIp")->getList();

if (empty($ipIdList)) {
    die("no ip address binded need to add monitor!");
}

// 获取需要添加监控的IP
$ipIdSet = array_column($ipIdList, 'ip_id');
$serverIpObj = model('ServerIp');
$thisWhere = [
    'is_delete' => 0,
    'ip_id' => $ipIdSet,
    'belong_type' => 0,
    'ip_domain_id' => 0,
    'dnspod_id' => 0,
    'monitor_id' => 0
];
$ipList = $serverIpObj->getList("ip_id, ip, ip_domain_id, dnspod_id, monitor_id", $thisWhere);
if (empty($ipList)) {
    die("no ip address need to add monitor!");
}
    
$ipListTemp = $ipset = array();
foreach ($ipList as $ipInfo) {
    $ipListTemp[$ipInfo['ip']] = $ipInfo;
    $ipset[] = $ipInfo['ip'];
}

// 添加监控
$ipMonitorObj = new IpMonitor();
$response = $ipMonitorObj->addIpMonitor($ipset);

if (1 == $response['error'] || empty($response['data'])) {
    die("XXX ip addresses binded add monitor failed, please operate again!");
}

$ipData = array();
foreach ($response['data'] as $ip => $recordInfo) {
    $ipData[] = [
        'ip_id' => $ipListTemp[$ip]['ip_id'],
        'dnspod_id' => $recordInfo['recordId'],
        'ip_domain_id' => $recordInfo['ipDomainId'],
        'monitor_id' => $recordInfo['monitorId']
    ];
}

if (empty($ipData)) {
    die("XXX ip address binded had something wrong");
}

$dbRes = null;
$dbRes = $serverIpObj->insert($ipData, true);

if (!$dbRes) {
    die("XXX ip address binded update database failed!");
} else {
    die("YYY ip address binded add monitor success!");
}

die("The script is end");
